import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store= new Vuex.Store({
  state: {
    cartList:[]
  },
  mutations: {
      addCount(state,payload){
         payload.count++
      },
      addToCart(state,payload){
        //默认不选中
        payload.checked=false
        payload.count=1
        state.cartList.push(payload)
      }
  },
  //actions 异步 可以返回 Promise
  actions: {
    addCart(context,payload){
      //payload新添加的商品
      // let oldProduct=null
      // for(let item of state.cartList){
      //   if(item.iid===payload.iid){
      //     oldProduct=item
      //   }
      // }
      return new Promise((resolve,reject)=>{
          //查找之前数组中是否有该商品
          let oldProduct=context.state.cartList.find(function(item){
            return item.iid===payload.iid
          })
          if(oldProduct){
            context.commit('addCount',oldProduct)
            resolve('当前商品数量+1')
          }else{
            // payload.count=1
            context.commit('addToCart',payload)
            // context.state.cartList.push(payload)
            resolve('添加了新的商品')
          }
      })
    }
  },
  modules: {
  }
})
export default store
